import store from '@/store';
import router, { resetRouter } from '@/router/index';
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import { Session } from '@/utils/storage';

// 创建 axios 实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API_ALIYUN,
    timeout: 50000,
    headers: { 'Content-Type': 'application/json' },
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么 token
        config.headers.common["Authorization"] = "Bearer ADMIN-TEMPLATE";
        // if (localStorage.getItem('token')) {
        //     config.headers.common["Authorization"] = "Bearer " + `${localStorage.getItem('token')}`;
        // }
        // let captchaKey = localStorage.getItem('captchaKey');
        // config.headers["Captcha-Key"] = captchaKey;
        // if (process.env.NODE_ENV === 'production') {
        //     config.url = config.url.substring(4);
        // }
        // if (process.env.NODE_ENV === 'production') {
        //   let url = config.url;
        //   console.log(url)
        //   if (url.indexOf('/aliyun-api') != -1) {
        //     url = url.replace('/aliyun-api', '');
        //   }
        //   config.url = url;
        // }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        const res = response.data;
        if (res.code && res.code !== 200) {
            if (res.code === 401 || res.code === 4001 || res.businessCode === 401 || res.businessCode === 4001) {
                // 清除浏览器全部临时缓存
                localStorage.clear();
                router.push('/login');
                store.commit('setMenuData', {});
                resetRouter(); // 重置路由
                let msg = res.msg;
                if (!msg) {
                    msg = '权限不足！您已被强制登出，请授权后重新登录。';
                }
                MessageBox.alert(msg, '提示', {})
                    .then(() => { })
                    .catch(() => { });
            }

            if (res.code === 500) {
                if (res.businessCode) {
                    return response.data;
                }
                Message.error('接口错误，请联系管理员。错误原因：' + res.msg);
            }
            return Promise.reject(service.interceptors.response.error);
        } else {
            return response.data;
        }
    },
    (error) => {
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            Message.error('网络超时');
        } else if (error.message == 'Network Error') {
            Message.error('网络连接错误');
        } else {
            Message.error(error.response.data.message);
        }
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default service;
